from flask import Blueprint, render_template, request, jsonify, current_app, url_for, redirect
from app.models import Video, Category
from app import db
from app.utils.qiniu_storage import upload_to_qiniu, delete_from_qiniu
import os
import time
from werkzeug.utils import secure_filename

admin = Blueprint('admin', __name__)

@admin.route('/admin/')
def index():
    try:
        categories = Category.query.all()
        videos = Video.query.order_by(Video.created_at.desc()).all()
        current_app.logger.info("Admin index accessed")
        return render_template('admin/index.html', categories=categories, videos=videos)
    except Exception as e:
        current_app.logger.error(f"Admin index error: {str(e)}")
        return str(e), 500

@admin.route('/admin/upload', methods=['POST'])
def upload():
    try:
        # 获取表单数据
        title = request.form.get('title')
        category_id = request.form.get('category_id')
        description = request.form.get('description')
        cover_file = request.files.get('cover')
        video_file = request.files.get('video')

        if not all([title, category_id, cover_file, video_file]):
            return jsonify({'success': False, 'error': '请填写所有必填字段'})

        # 创建临时目录
        temp_dir = os.path.join(current_app.instance_path, 'temp')
        os.makedirs(temp_dir, exist_ok=True)

        try:
            # 处理文件上传
            timestamp = int(time.time())
            cover_filename = f'covers/{timestamp}_{secure_filename(cover_file.filename)}'
            video_filename = f'videos/{timestamp}_{secure_filename(video_file.filename)}'

            # 保存临时文件
            cover_temp = os.path.join(temp_dir, f'cover_{timestamp}')
            video_temp = os.path.join(temp_dir, f'video_{timestamp}')
            
            cover_file.save(cover_temp)
            video_file.save(video_temp)

            # 上传到七牛云
            cover_result = upload_to_qiniu(cover_temp, cover_filename)
            video_result = upload_to_qiniu(video_temp, video_filename)

            # 保存到数据库
            video = Video(
                title=title,
                description=description,
                category_id=category_id,
                cover_url=cover_result['url'],
                video_url=video_result['url'],
                status='published'
            )
            db.session.add(video)
            db.session.commit()

            return jsonify({
                'success': True,
                'message': '上传成功',
                'data': {
                    'id': video.id,
                    'title': video.title,
                    'cover_url': f"https://jkl7n.lingbankeji.com/covers/{cover_result['key']}",
                    'video_url': f"https://jkl7n.lingbankeji.com/videos/{video_result['key']}"
                }
            })

        finally:
            # 清理临时文件
            if os.path.exists(cover_temp):
                os.remove(cover_temp)
            if os.path.exists(video_temp):
                os.remove(video_temp)

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"上传失败: {str(e)}")
        return jsonify({'success': False, 'error': str(e)}), 500

@admin.route('/admin/video/<int:video_id>', methods=['DELETE'])
def delete_video(video_id):
    try:
        video = Video.query.get_or_404(video_id)
        
        # 删除七牛云文件
        if video.cover_url:
            delete_from_qiniu(video.cover_url)
        if video.video_url:
            delete_from_qiniu(video.video_url)
            
        # 删除数据库记录
        db.session.delete(video)
        db.session.commit()
        
        return jsonify({'success': True})
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除失败: {str(e)}")
        return jsonify({'success': False, 'error': str(e)}), 500
# ... 其他管理路由 ... 
